<template>
  <div class="app-container">
    <image-upload v-model="imageUrl" :limit="1"></image-upload>
    <el-row :gutter="10" class="operation" v-if="productList && productList.length > 0">
      <el-col :span="2" style="text-align: center">
        <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="onCheckAll">全选</el-checkbox>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" :disabled="multiple" @click="addCollectTask">
          添加采集任务
        </el-button>
      </el-col>
    </el-row>
    <div class="sellerproduct-list" v-loading="loading">
      <div class="sellerproduct-list-item"
           v-for="(item, index) in productList"
           :key="index">
        <el-card>
          <div>
            <div :style="{ padding: '10px' }">
              <div class="pCheckbox">
                <el-checkbox v-model="item.isChecked" @change="onItemChange($event, index)">
                  <img v-if="item.imageUrl" :src="item.imageUrl" class="sellerproduct-list-item-image">
                </el-checkbox>
              </div>
              <div class="sellerproduct-list-item-info" @click="openCollectLink(item.detailUrl)">
                <span class="info-price">{{ item.price.value }}</span>
                <div class="info-title">{{ item.title }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

  </div>
</template>

<script>
import {queryImageHash} from "@/api/picture/optimizeTask"
import axios from "axios";
import {addCollectProductTask} from "@/api/gather/collectProductTask";
import store from "@/store";

export default {
  name: "SellerProduct",
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: '',
      loading: false,
      imageUrl: undefined,
      isIndeterminate: false,
      isCheckAll: false,
      sellerProductList: [],//产品列表
      multiple: true,
      selectProductList: []
    };
  },
  computed: {
    productList() {
      let productList = this.sellerProductList;
      productList.forEach((item) => {
        // const imageURLsArr = (item.imageURLs || '').split(';').filter(i => !!i)
        // const newArr = []
        // imageURLsArr.forEach(val => {
        //   if (val.indexOf('http://') === -1 && val.indexOf('https://') === -1) {
        //     newArr.push(store.getters.domain + val)
        //   } else {
        //     newArr.push(val)
        //   }
        // })
        // item.imageURLs = newArr.toString();
        this.$set(item, "isChecked", false);
      });
      return productList;
    },
  },
  watch: {
    "imageUrl": {
      handler(newVal, oldVal) {
        console.log("新的值:" + newVal);
        console.log("旧的值:" + oldVal);
        if (newVal) {
          this.getImageHash()
        }
      }
    }
  },
  created() {

  },
  methods: {
    getImageHash() {
      this.$modal.loading("搜索相关产品，请稍候...");
      let url = 'https://file.pbb2c.com/' + this.imageUrl
      axios.post('https://api.aliseeks.com/upload/image?url=' + url).then(res => {
        console.log('res', res)
        // this.loading = false
        if (res.data.hash) {
          this.getImgProductList(res.data.hash)
        }
      }).catch(err => {
        console.log('err', err)
        this.$message.error('系统错误，请联系管理员！')
        this.$modal.closeLoading();
      })
    },
    getImgProductList(hash) {
      // this.loading = true
      this.$modal.loading("搜索相关产品，请稍候...");
      axios.post('https://api.aliseeks.com/search/image', {
        "page": 1,
        "fsKey": hash,
        "currency": "USD",
        "language": "en_US",
        "category": "",
        "locale": "en_US",
        "provider": "ali",
        "shipToCountry": "en_US"
      }).then(res => {
        console.log('res', res)
        let list = res.data.items
        this.loading = false
        this.$modal.closeLoading();
        this.$message.success('搜图成功！')
        this.sellerProductList = list
      })
    },
    // 添加采集任务
    addCollectTask() {
      this.$confirm('是否确定将选中商品添加到采集任务中？').then(() => {
        let data = {
          category: '1',//速卖通
          collectUrl: this.selectProductList.join('\n').toString(),//采集链接
        }
        addCollectProductTask(data).then(res => {
          this.$message.success(res.msg)
        })
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 打开采集链接
    openCollectLink(url) {
      window.open(url)
    },
    //当点击全选的时候
    onCheckAll(checked) {
      const flag = checked;
      let proSelect = [];
      if (flag) {
        this.multiple = false
        this.sellerProductList.forEach((item) => {
          item.isChecked = true;
          proSelect.push(item.detailUrl);
        });
      } else {
        this.multiple = true
        this.sellerProductList.forEach((item) => {
          item.isChecked = false;
          proSelect = []
        });
      }
      this.selectProductList = proSelect
      // console.log('全选proSelect', proSelect)
      this.isIndeterminate = false
    },
    //当点击单个选中的时候
    onItemChange(checked, productIndex) {
      console.log('选择单个', checked, productIndex)
      const flag = checked;
      var isAll = true;
      let proSelect = []
      this.sellerProductList.forEach((item, index) => {
        if (productIndex == index) {
          // console.log('index', index, productIndex)
          if (flag) {
            item.isChecked = true;
            // this.selectProductList.push(item.detailUrl);
          } else {
            item.isChecked = false;
            // this.selectProductList.slice(index, 1)
          }
        }
        if (item.isChecked == false) {
          isAll = false;
        }
        if (item.isChecked) {
          proSelect.push(item.detailUrl);
        }
      });
      this.selectProductList = proSelect
      this.isCheckAll = isAll;
      // this.sellerProductList.forEach((item) => {
      //   if (item.isChecked) {
      //     proSelect.push(item.detailUrl);
      //   }
      // });
      console.log('proSelect', proSelect)
      this.multiple = !proSelect.length
      this.isIndeterminate = proSelect.length > 0 && proSelect.length < this.sellerProductList.length;
    },
  }
};

</script>

<style lang="scss">
.operation {
  border-top: 1px solid #DFDFDF;
  border-bottom: 1px solid #DFDFDF;
  padding: 10px 0;
  margin: 20px 0;
  display: flex;
  align-items: center;

  .operation-item {
    position: relative;
    font-size: 14px;
    text-align: center;

    &:before {
      content: '';
      width: 1px;
      height: 16px;
      background-color: #DFDFDF;
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -8px;
    }

    .el-icon-upload2 {
      color: #FF6A07;
    }

    .active {
      color: #FF6A07;
    }

    div {
      cursor: pointer;
    }
  }
}

.sellerproduct-list {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .sellerproduct-list-item {
    width: calc((100% - 60px) / 6);
    margin: 0 5px 10px 5px;
    cursor: pointer;

    .pCheckbox {
      width: 100%;

      .el-checkbox {
        width: 100%;
        position: relative;

        .el-checkbox__input {
          position: absolute;
          top: 2px;
          right: 2px;
        }

        .el-checkbox__label {
          padding: 0;
          display: block;
          line-height: normal;

          .sellerproduct-list-item-image {
            width: 100%;
            height: 248px;
            object-fit: cover;
            border: 1px solid #999999;
          }
        }
      }
    }

    .sellerproduct-list-item-info {
      margin: 0 -5px;
      padding: 10px 0 0;

      .info-price {
        font-size: 16px;
        line-height: 20px;
        height: 20px;
        color: #1890ff;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        display: block;
      }

      .info-title {
        font-size: 12px;
        line-height: 16px;
        color: #999999;
        margin-top: 5px;
        display: -webkit-box;
        -webkit-line-clamp: 4;
        -webkit-box-orient: vertical;
        overflow: hidden;
        height: 64px;
      }

      .info-brandName {
        font-size: 12px;
        line-height: 16px;
        color: #999999;
        margin-top: 5px;
        height: 28px;
      }
    }

    .el-card__body {
      padding: 0;
    }
  }
}


.text {
  display: block;
  font-size: 12px;
  padding: 0 10px;
}

.color {
  color: #1890ff;
  cursor: pointer;
}

.flex {
  .el-form-item__content {
    flex: 1;
    display: flex;
    align-items: center;

    .el-input {
      width: 80px;
    }
  }

  .span {
    font-size: 12px;
    line-height: 36px;
    color: #999999;
    padding: 0 10px;
  }
}


.el-drawer__body {
  overflow: hidden;

  .demo-drawer__content {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-form {
      overflow: auto;
      flex: 1;
    }

    .demo-drawer__footer {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px 0;
      border-top: 1px solid #DCDFE6;
    }
  }
}
</style>
